/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
import React, { useEffect, useState } from 'react';
import { StatusBar, Text,TouchableOpacity, View ,Image, ScrollView, ImageBackground, Alert, TouchableHighlight} from 'react-native';
import AsyncChildComponent from '../learn/AsyncChildComponent';
import AsyncStorage from '@react-native-async-storage/async-storage'; 
import styles from './DialogStyles';
import { NativeModules } from 'react-native';
import BottomSheet, { BottomSheetMethods } from '@devvie/bottom-sheet';
import RuleModal from '../../components/RuleModal';
import ruleConfig from './rules';
const {  WeChat } = NativeModules;
const Toolshop = ({route,navigation})=>{
  const [purchases, setPurchases] = useState<{[key: string]: number}>({});
  const [showRules, setShowRules] = useState(false);
  const init = async()=>{
    let m = await AsyncStorage.getItem('awardstar'); 
      if ( m === null ){
        await AsyncStorage.setItem('awardstar', '10'); 
      }
  }
  useEffect(() => {
    const loadPurchases = async () => {
      try {
        const savedPurchases = await AsyncStorage.getItem('purchases');
        if (savedPurchases) {
          setPurchases(JSON.parse(savedPurchases));
        }
      } catch (error) {
        console.error('读取购买记录失败:', error);
      }
    };
    init();
    loadPurchases();
  }, []);
  const items = [
    { id: '1', image: 'asset:/award/adventure_store1.png' },
{ id: '2', image: 'asset:/award/adventure_store2.png' },
{ id: '3', image: 'asset:/award/adventure_store3.png' },
{ id: '4', image: 'asset:/award/adventure_store4.png' },
{ id: '5', image: 'asset:/award/adventure_store5.png' },
{ id: '6', image: 'asset:/award/adventure_store6.png' },
{ id: '7', image: 'asset:/award/adventure_store7.png' },
{ id: '8', image: 'asset:/award/adventure_store8.png' },
{ id: '9', image: 'asset:/award/adventure_store9.png' },
{ id: '10', image: 'asset:/award/adventure_store10.png' },
{ id: '11', image: 'asset:/award/adventure_store11.png' },
{ id: '12', image: 'asset:/award/adventure_store12.png' },
{ id: '13', image: 'asset:/award/adventure_store13.png' },
{ id: '14', image: 'asset:/award/adventure_store14.png' },
{ id: '15', image: 'asset:/award/adventure_store15.png' },
{ id: '16', image: 'asset:/award/adventure_store16.png' },
{ id: '17', image: 'asset:/award/adventure_store17.png' },
{ id: '18', image: 'asset:/award/adventure_store18.png' }
    // ... 添加更多商品
  ];
 
  const handlePurchase = async (itemId: string) => {
    let m =await AsyncStorage.getItem('awardstar');
    let n = Number(m);
        if (n >= 5){
          await AsyncStorage.setItem('awardstar',`${n - 5}`);
          try {
            const newPurchases = {
              ...purchases,
              [itemId]: (purchases[itemId] || 0) + 1
            };
            setPurchases(newPurchases);
            await AsyncStorage.setItem('purchases', JSON.stringify(newPurchases));
          } catch (error) {
            console.error('保存购买记录失败:', error);
          }
          Alert.alert(
            '',
            '购买成功',
            [
              { text: '确定', onPress: () => console.log('Ask me later pressed')},

            ],
            { cancelable: false }
          );

        } else {
          Alert.alert(
            '',
            '星星不够，快去练习吧！',
            [
              { text: '确定', onPress: () => console.log('Ask me later pressed')},

            ],
            { cancelable: false }
          );
        }
    
  };

  return(
    <View style={{ resizeMode: 'contain',
      width: '100%',
      flex: 1,
      justifyContent: 'flex-end',backgroundColor:'blue'}}>
    <StatusBar
          hidden={false}
          backgroundColor="black"
          barStyle={ 'light-content'}
        />
        <ImageBackground
        resizeMode="stretch"
        style={ {flex: 1}}
        source={{ uri:'asset:/award/adventure_store_background.png' }}>
            <View  style={{flexDirection:'row',height:'10%',width:'100%',top:20,justifyContent:'center',alignContent:'center'}}>
            <TouchableOpacity style={{ width:'20%'}} onPress={()=>{navigation.goBack()}}>
               <Image  style={{resizeMode:'stretch',height:40,width:30}} source={{ uri:'asset:/award/adventure_store_back.png' }} />
             </TouchableOpacity>
              <View style={{ width:'60%'}}>
                
                </View>
             <TouchableOpacity style={{  }} onPress={()=>{setShowRules(true)}}>
               <Image  style={{resizeMode:'stretch',height:40,width:30}} source={{ uri:'asset:/award/adventure_store_rule.png' }} />
             </TouchableOpacity>
            </View>

            <ScrollView style={{flex: 1}}>
              <View style={{padding: 15}}>
                {items.map((item, index) => (
                  index % 2 === 0 && (
                    <View key={item.id} style={{flexDirection: 'row', justifyContent: 'space-between', marginBottom: 20}}>
                      <View style={{alignItems: 'center', width: '48%'}}>
                        <Image 
                          source={{ uri: item.image }} 
                          style={{width: 150, height: 150, resizeMode: 'contain'}} 
                        />
                        <View style={{ width:'60%',flexDirection:'row',justifyContent:'center',alignContent:'center'}}>
                          <Text style={{ fontWeight:'bold',color:'black',fontSize:30,top:5}}>5</Text>
                          <Image source={{ uri:'asset:/award/adventure_star.png' }} style={{height:30,width:30,top:'10%',resizeMode:'stretch'}} /> 
                        </View>
                        <TouchableOpacity
                          onPress={() => handlePurchase(item.id)}
                        >
                           <Image source={{ uri:'asset:/award/adventure_store_buy.png' }} style={{height:60,width:120,top:'10%',resizeMode:'stretch',margin:10,borderRadius:10}} />  
                        </TouchableOpacity>
                        <Text style={{marginTop: 5, fontSize: 14, color: '#666'}}>
                          已换取: {purchases[item.id] || 0}
                        </Text>
                      </View>
                      
                      {items[index + 1] && (
                        <View style={{alignItems: 'center', width: '48%'}}>
                          <Image 
                            source={{ uri: items[index + 1].image }} 
                            style={{width: 150, height: 150, resizeMode: 'contain'}} 
                          />
                          <View style={{ width:'60%',flexDirection:'row',justifyContent:'center',alignContent:'center'}}>
                          <Text style={{ fontWeight:'bold',color:'black',fontSize:30,top:5}}>5</Text>
                          <Image source={{ uri:'asset:/award/adventure_star.png' }} style={{height:30,width:30,top:'10%',resizeMode:'stretch'}} /> 
                        </View>
                          <TouchableOpacity  
                            onPress={() => handlePurchase(items[index + 1].id)}
                          >
                            <Image source={{ uri:'asset:/award/adventure_store_buy.png' }} style={{height:60,width:120,top:'10%',resizeMode:'stretch',margin:10,borderRadius:10}} />  
                          </TouchableOpacity>
                          <Text style={{marginTop: 5, fontSize: 14, color: '#666'}}>
                            已换取: {purchases[items[index + 1].id] || 0}
                          </Text>
                        </View>
                      )}
                    </View>
                  )
                ))}
              </View>
            </ScrollView>
        </ImageBackground>
             <RuleModal
        visible={showRules}
        onClose={() => setShowRules(false)}
        title={ruleConfig.title}
        rules={ruleConfig.rules}
        imagePath={ruleConfig.imagePath}
      />
      
    </View>
  );

};

export default Toolshop;